# -*-encoding: utf-8 -*-

from pyramid.view import view_config
from pyramid.view import view_defaults
from pyramid.response import Response
from pyramid.httpexceptions import HTTPFound
import json
from ..utils.Hash.HashUtil import HashUtil
from ..utils.Image.ImageUtil import ImageUtil
from ..utils.DB import MySqlCRUD
import time, os, uuid, shutil, hashlib
import base64
from ..utils.Queue import UploadTasks
from ..utils.SMS import MobSMS
from ..utils.User.User import User
from ..utils.Cache.TokenCache import TokenCache
from ..utils.Cache.ChecksumCache import ChecksumCache
import logging

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
log = logging.getLogger(__name__)

from AppBase import Base
class Creation(Base):

    @view_config(route_name='AppCreationUploadRoute', request_method='POST')
    def AppCreationUploadRoute(self):
        try:
            postParams =  self.request.POST
            tel = postParams.getone('tel')
            tString = postParams.getone('tString')
            eString = postParams.getone('eString')
            tokenString = postParams.getone('tokenString')
            csc = postParams.getone('csc')
            uploadFile = postParams.getone('image_file')
            input_file = uploadFile.file
            suffix = postParams.getone('suffix')

            log.debug('[category]' + postParams.getone('category'))
            log.debug('[name]' + postParams.getone('name'))
            log.debug('[material]' + postParams.getone('material'))
            log.debug('[size]' + postParams.getone('size'))
            log.debug('[weight]' + postParams.getone('weight'))
            log.debug('[aperture]' + postParams.getone('aperture'))
            log.debug('[price]' + postParams.getone('price'))
            log.debug('[description]' + postParams.getone('description'))
        except Exception, e:
            map = {'RetCode': '143', 'message': '更新抠制的素材失败!', 'data': '无参数!'}
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return Response(jsonStr)
        tmpTokenString = self.calculateToken(tString, tel)
        cache = ChecksumCache()
        if (eString <> HashUtil.getStringMD5(tel + tString)) or (tokenString <> tmpTokenString):
            map = {'RetCode': '145', 'message': '流程验证失败!', 'data': '请重新登录'}
            cache.deleteCache(tel)
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return Response(jsonStr)
        tmpCS = cache.getCache(tel)
        if tmpCS <> csc:
            map = {'RetCode': '145', 'message': '流程验证失败!', 'data': '重新提交请求'}
            cache.deleteCache(tel)
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return Response(jsonStr)
        # The file instance
        fileMD5 = HashUtil.getFileMD5(input_file.read())
        fileName = fileMD5 + '.' + suffix
        log.debug('[CREATION][MD5]' + fileMD5)

        # The file path
        file_path = os.path.join('/media/img', suffix, fileMD5[0: 2], fileMD5[2: 4], fileName)
        temp_file_path = file_path + '.tmp'
        input_file.seek(0)
        folderName = file_path[0: file_path.rfind('/') + 1]
        if not os.path.exists(folderName):
            os.makedirs(folderName)

        with open(temp_file_path, 'wb') as output_file:
            shutil.copyfileobj(input_file, output_file)
        os.rename(temp_file_path, file_path)

        thumb_path = os.path.join('/media/thumb', fileMD5[0: 2], fileMD5[2: 4], fileName)
        thumb_path = thumb_path.replace(suffix, 'jpg')
        ImageUtil.make_thumb(file_path, thumb_path, 200, 100)

        map = {'RetCode': '', 'message': '', 'data': ''}
        try:
            #'1'表示用户制作
            #UploadTasks.uploadCollectionByQueue(fileMD5, tel, '1')
            UploadTasks.uploadImgByQueue(fileMD5, file_path, tel, postParams.getone('category'), \
                postParams.getone('name'), postParams.getone('material'), postParams.getone('size'), postParams.getone('weight'), \
                postParams.getone('aperture'), postParams.getone('price'), postParams.getone('description'), '')
                #postParams.getone('aperture'), postParams.getone('price'), postParams.getone('description'), postParams.getone('url'))
            map = {'RetCode': '0', 'message': '更新抠制的素材成功!', 'data': file_path}
        except Exception, e:
            log.error(e)
            map = {'RetCode': '143', 'message': '更新抠制的素材失败!', 'data': file_path}
        jsonStr = json.dumps(map, ensure_ascii=False)
        jsonStr = jsonStr.replace('/media', '/static')
        log.debug(jsonStr)
        return Response(jsonStr)

    @view_config(route_name='AppCreationRemoveRoute', request_method='POST')
    def AppCreationRemoveRoute(self):
        try:
            postParams =  self.request.POST
            tel = postParams.getone('tel')
            tString = postParams.getone('tString')
            eString = postParams.getone('eString')
            tokenString = postParams.getone('tokenString')
            csc = postParams.getone('csc')
            md5 = postParams.getone('data')
        except Exception, e:
            map = {'RetCode': '146', 'message': '删除我的素材失败!', 'data': '无参数!'}
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return Response(jsonStr)
        tmpTokenString = self.calculateToken(tString, tel)
        cache = ChecksumCache()
        if (eString <> HashUtil.getStringMD5(tel + tString)) or (tokenString <> tmpTokenString):
            map = {'RetCode': '145', 'message': '流程验证失败!', 'data': '请重新登录'}
            cache.deleteCache(tel)
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return Response(jsonStr)
        tmpCS = cache.getCache(tel)
        if tmpCS <> csc:
            map = {'RetCode': '145', 'message': '流程验证失败!', 'data': '重新提交请求'}
            cache.deleteCache(tel)
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return Response(jsonStr)
        # The file instance
        map = {'RetCode': '', 'message': '', 'data': ''}
        try:
            UploadTasks.deleteMaterialUserInfoByQueue(md5, tel)
            map = {'RetCode': '0', 'message': '删除我的收藏成功!', 'data': md5}
        except Exception, e:
            log.error(e)
            map = {'RetCode': '146', 'message': '删除我的收藏失败!', 'data': file_path}
        jsonStr = json.dumps(map, ensure_ascii=False)
        jsonStr = jsonStr.replace('/media', '/static')
        log.debug(jsonStr)
        return Response(jsonStr)
